# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/10/28 14:35
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : basic_threshold.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""


def basic_threshold(src, init_thresh, delta_thresh=0.1):
    """
    实现单通道图像(灰度图)全局基本阈值分割
    :param src: 待分割图像数组
    :param init_thresh: 初始阈值
    :param delta_thresh: 阈值误差限
    :return:阈值分割图像数组,基本全局阈值
    """
    max_val, min_val = src.max(), src.min()
    if init_thresh >= max_val or init_thresh < min_val:  # 判断输入初始阈值是否合法，不合法抛出异常
        raise ValueError("初始阈值init_thresh超出合理范围[{},{}]".format(min_val, max_val))
    else:
        import numpy as np
        great_mu = src[src > init_thresh].mean()
        leq_mu = src[src <= init_thresh].mean()
        temp_thresh1 = init_thresh
        temp_thresh2 = np.mean(np.array([great_mu, leq_mu], dtype=np.float64))
        while True:
            if np.abs(temp_thresh2 - temp_thresh1) < delta_thresh:  # 当相邻两次阈值之差小于指定值，认为收敛，结束迭代
                return np.piecewise(src, [src < temp_thresh2], [0, 255]), np.round(temp_thresh2, decimals=0)
            great_mu = src[src > temp_thresh2].mean()  # 逐次迭代
            leq_mu = src[src <= temp_thresh2].mean()
            temp_thresh2, temp_thresh1 = np.mean(np.array([great_mu, leq_mu], dtype=np.float64)), temp_thresh2


if __name__ == '__main__':
    im_path = "../experiment_fig/circle.tif"
    font_path = "C:/Windows/Fonts/simhei.ttf"
    from skimage.io import imread
    from PIL import Image
    from DIP_experiment_5.util import contrast_show, histogram
    import numpy

    im_arr = imread(im_path)
    print("原始图像灰度级数组:{}".format(numpy.unique(im_arr)))
    im_obj = Image.fromarray(im_arr)
    im_dict = {"原始图像直方图": im_obj}
    histogram(im_dict, (1, 1), font=font_path)
    seg_im, threshold = basic_threshold(im_arr, init_thresh=120)
    images_dict = {"原始图像": im_arr, f"阈值灰度{threshold}分割图像": seg_im}
    contrast_show(images_dict, (1, 2), font=font_path)
